package com.data.modules.ai.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.conditions.query.LambdaQueryChainWrapper;
import com.baomidou.mybatisplus.extension.conditions.update.LambdaUpdateChainWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.data.common.api.vo.Result;
import com.data.common.aspect.annotation.AutoLog;
import com.data.common.system.base.controller.BootController;
import com.data.common.system.query.QueryGenerator;
import com.data.common.util.IPUtils;
import com.data.common.util.SpringContextHolder;
import com.data.common.util.SpringContextUtils;
import com.data.modules.ai.entity.AiJs;
import com.data.modules.ai.service.IAiJsService;
import com.data.modules.log.entity.WsLog;
import com.data.modules.log.service.IWsLogService;
import com.data.modules.message.websocket.WebSocket;
import com.data.modules.online.config.exception.BusinessException;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import me.zhyd.oauth.utils.IpUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.websocket.Session;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @Description: ai_js 脚本表
 * @Author: data-boot
 * @Date: 2022-04-15
 * @Version: V1.0
 */
@Api(tags = "ai_js 脚本表")
@RestController
@RequestMapping("/ai/js")
@Slf4j
public class AiJsController extends BootController<AiJs, IAiJsService> {

    @Autowired
    private IAiJsService aiJsService;

    @Autowired
    private IWsLogService wsLogService;

    /**
     * 分页列表查询
     *
     * @param aiJs
     * @param pageNo
     * @param pageSize
     * @param req
     * @return
     */
    @AutoLog(value = "ai_js 脚本表-分页列表查询")
    @ApiOperation(value = "ai_js 脚本表-分页列表查询", notes = "ai_js 脚本表-分页列表查询")
    @GetMapping(value = "/list")
    public Result<?> queryPageList(AiJs aiJs,
                                   @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
                                   @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize,
                                   HttpServletRequest req) {
        QueryWrapper<AiJs> queryWrapper = QueryGenerator.initQueryWrapper(aiJs, req.getParameterMap());
        LambdaQueryWrapper<AiJs> wrapper = queryWrapper.lambda();
        wrapper.orderByDesc(AiJs::getCreateTime);
        Page<AiJs> page = new Page<AiJs>(pageNo, pageSize);
        IPage<AiJs> pageList = aiJsService.page(page, wrapper);
        return Result.OK(pageList);
    }

    /**
     * 添加
     *
     * @param aiJs
     * @return
     */
    @AutoLog(value = "ai_js 脚本表-添加")
    @ApiOperation(value = "ai_js 脚本表-添加", notes = "ai_js 脚本表-添加")
    @PostMapping(value = "/add")
    public Result<?> add(@RequestBody AiJs aiJs) {
        log.info("脚本表-添加 json = {}", JSONObject.toJSONString(aiJs));
        aiJsService.save(aiJs);
        return Result.OK("添加成功！");
    }

    @AutoLog(value = "ai_js 脚本表-推送到服务端")
    @ApiOperation(value = "ai_js 脚本表-推送到服务端", notes = "ai_js 脚本表-推送到服务端")
    @PostMapping(value = "/publish")
    public Result<?> publish(@RequestBody AiJs aiJs) {
        log.info("脚本表-推送 json = {}", JSONObject.toJSONString(aiJs));
        LambdaQueryWrapper<AiJs> wrapper = new LambdaQueryWrapper<AiJs>()
                .eq(AiJs::getVersion,aiJs.getVersion())
                .eq(AiJs::getJsName, aiJs.getJsName());
        if (aiJsService.count(wrapper)>0){
            return Result.error("当前版本已经存在！");
        }else {
            aiJs.setIp(IPUtils.getIpAddr(SpringContextUtils.getHttpServletRequest()));
            aiJs.setUpdateTime(new Date());
            aiJsService.save(aiJs);
        }
        return Result.OK("推送成功！");
    }

    @ApiOperation(value = "ai_js 客户端列表", notes = "ai_js 客户端列表")
    @GetMapping(value = "/queryClientList")
    public Result<?> queryClientList(AiJs aiJs) {
        log.info("客户端列表 json = {}", JSONObject.toJSONString(aiJs));
        List<WsLog> list = WebSocket.sessionPool.entrySet().stream().map(k->{
            WsLog wsLog = new WsLog();
            wsLog.setId(k.getKey());
            wsLog.setDeviceId(k.getKey());
            return wsLog;
        }).collect(Collectors.toList());
        return Result.OK(list);
    }

    @ApiOperation(value = "ai_js 脚本表-推送到客户端", notes = "ai_js 脚本表-推送到客户端")
    @PutMapping(value = "/pubScriptToClient")
    public Result<?> pubScriptToClient(@RequestBody AiJs aiJs) {
        log.info("pubScriptToClient:{}", JSON.toJSONString(aiJs));
        try{
            aiJsService.pubScriptToClient(aiJs);
        }catch (Exception e){
            log.error(e.getMessage(),e);
            return Result.error("发布失败"+e.getMessage());
        }

        return Result.OK();
    }

    /**
     * 编辑
     *
     * @param aiJs
     * @return
     */
    @AutoLog(value = "ai_js 脚本表-编辑")
    @ApiOperation(value = "ai_js 脚本表-编辑", notes = "ai_js 脚本表-编辑")
    @PutMapping(value = "/edit")
    public Result<?> edit(@RequestBody AiJs aiJs) {
        aiJsService.updateById(aiJs);
        return Result.OK("编辑成功!");
    }

    /**
     * 通过id删除
     *
     * @param id
     * @return
     */
    @AutoLog(value = "ai_js 脚本表-通过id删除")
    @ApiOperation(value = "ai_js 脚本表-通过id删除", notes = "ai_js 脚本表-通过id删除")
    @DeleteMapping(value = "/delete")
    public Result<?> delete(@RequestParam(name = "id", required = true) String id) {
        aiJsService.removeById(id);
        return Result.OK("删除成功!");
    }

    /**
     * 批量删除
     *
     * @param ids
     * @return
     */
    @AutoLog(value = "ai_js 脚本表-批量删除")
    @ApiOperation(value = "ai_js 脚本表-批量删除", notes = "ai_js 脚本表-批量删除")
    @DeleteMapping(value = "/deleteBatch")
    public Result<?> deleteBatch(@RequestParam(name = "ids", required = true) String ids) {
        this.aiJsService.removeByIds(Arrays.asList(ids.split(",")));
        return Result.OK("批量删除成功!");
    }

    /**
     * 通过id查询
     *
     * @param id
     * @return
     */
    @AutoLog(value = "ai_js 脚本表-通过id查询")
    @ApiOperation(value = "ai_js 脚本表-通过id查询", notes = "ai_js 脚本表-通过id查询")
    @GetMapping(value = "/queryById")
    public Result<?> queryById(@RequestParam(name = "id", required = true) String id) {
        AiJs aiJs = aiJsService.getById(id);
        if (aiJs == null) {
            return Result.error("未找到对应数据");
        }
        return Result.OK(aiJs);
    }

    /**
     * 导出excel
     *
     * @param request
     * @param aiJs
     */
    @RequestMapping(value = "/exportXls")
    public ModelAndView exportXls(HttpServletRequest request, AiJs aiJs) {
        return super.exportXls(request, aiJs, AiJs.class, "ai_js 脚本表");
    }

    /**
     * 通过excel导入数据
     *
     * @param request
     * @param response
     * @return
     */
    @RequestMapping(value = "/importExcel", method = RequestMethod.POST)
    public Result<?> importExcel(HttpServletRequest request, HttpServletResponse response) {
        return super.importExcel(request, response, AiJs.class);
    }

}
